init('http');
(function(){
	var StringUtils = require('StringUtils'),
	    log         = require('Log').create('http');
	
	var format = StringUtils.format;
	
	var _ajax = function(params){
		log.debug(params.url);
		//console.log(params);
    	_ajaxDefaults(params);
    	
    	var xmlhttp;
		if( window.XMLHttpRequest ){
			xmlhttp=new XMLHttpRequest();
		}else{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.open(params.method, params.url, true);
		for(member in params.headers)
			xmlhttp.setRequestHeader(member, params.headers[member]);
		xmlhttp.onreadystatechange=function(){
			log.trace(xmlhttp);
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
				if( params.onSuccess && xmlhttp.responseText )
					params.onSuccess(eval('('+xmlhttp.responseText+')'), xmlhttp);
				else if( params.onError && !xmlhttp.responseText )
					params.onError('Not found', xmlhttp);
			}else if(xmlhttp.readyState == 4 && params.onError){
				params.onError(xmlhttp.responseText, xmlhttp);
			}
		}
		xmlhttp.send(params.body);
		return xmlhttp;
    };
    
    var _ajaxDefaults = function(params){
    	if( !params.method ) params.method = 'GET';
    	if( !params.url ) throw 'URL required';
    };
	
    var http = function(){
    	
    };
	http.prototype = {
		request : function(options, callback){
			var body = '';
			var req  = {
				on : function(event, callback){
					if( !this[event] )
						this[event] = callback;
				},
				end : function(data){
					body += data;
					_ajax({
						url : format('http://${host}:${port}${path}', options)
						,method : options.method
						,onSuccess : function(text, xmlhtpp){
							var response = {
								on : function(name, callback){
									this[name] = callback;
								}
							};
							callback(response);
							if( response.data )
								response.data(JSON.stringify(text));
							if( response.end )
								response.end();
						}
						,onError : function(text, xmlhttp){
							if( req.error )
								req.error(text);
						}
						,body : body
						,headers : options.headers
					});
				},
				write : function(data){
					body += data;
				},
				setHeader : function(key, value){
					if(!options.headers) options.headers = {};
					if(key != 'content-length')
						options.headers[key] = value;
				}
			}
			return req;
		}
	}
	module.exports = new http();
})();